<?php

namespace app\common\helper;

use app\common\exception\BusinessException;
use Firebase\JWT\JWT;
use \Exception;
use think\facade\Config;
use think\facade\Request;

class JwtHelper
{
    /**
     * 签发组织
     * @var string
     */
    private static $iss = 'https://www.5b1.cn';

    /**
     * 签发作者
     * @var string
     */
    private static $aud = 'https://www.5b1.cn';

    /**
     * Jwt的信息
     * @var array
     */
    public static $info = [];

    /**
     * 校验Jwt+获取用户Id
     * @param string $jwt
     * @return int
     * @throws Exception
     */
    public static function verify(string $jwt): int
    {
        $key = Config::get('jwt.key');
        $key = md5($key);
        try {
            $jwtAuth = json_encode(JWT::decode($jwt, $key, ['HS256']));
            $authInfo = json_decode($jwtAuth, true);
            if (empty($authInfo['user_id'])) {
                throw new BusinessException('Token验证不通过,用户不存在');
            }
            return $authInfo['user_id'];
        } catch (Exception $ex) {
            throw new BusinessException('Token验证不通过,' . $ex->getMessage());
        }
    }

    /**
     * 创建
     * @param int $userId
     * @param int $expire
     * @return string
     */
    public static function create(int $userId, int $expire): string
    {
        $key = Config::get('jwt.key');
        $key = md5($key);
        $time = time();
        $expire = $time + $expire;
        $token = [
            "user_id" => $userId,
            "ip" => Request::ip(),
            "iss" => static::$iss,
            "aud" => static::$aud,
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        ];
        return JWT::encode($token, $key);
    }
}